//
//  WiLiLoginRequest.m
//  WULIHH
//
//  Created by tang on 16/4/12.
//  Copyright © 2016年 tang. All rights reserved.
//

#import "WiLiLoginRequest.h"
#import "AFNetworking.h"
#import "Header.h"

//#import "AFHTTPRequestOperation.h"
@implementation WiLiLoginRequest


//登录
+ (id)requestUserLogin:(NSString *)openID withUserName:(NSString *)name withImage:(NSString *)imageUrl withPlatForm:(NSString *)platString
{
    
    
    NSString *string = [NSString stringWithFormat:@"%@%@",hostName, yonghudengluAPI];
    NSDictionary *dic = @{@"source":platString,
                          @"openId":openID,
                          @"iconUrl":imageUrl,
                          @"nickname":name};

    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"1.0" forHTTPHeaderField:@"X-APP-VERSON"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    
    
    [manager POST:string parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        // 这里可以获取到目前的数据请求的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 请求成功，解析数据
        //        NSLog(@"%@", responseObject);
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        
        [[NSUserDefaults standardUserDefaults] setValue:dic forKey:@"user"];
        [[NSUserDefaults standardUserDefaults] setValue:platString forKey:@"platform"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:yonghudenglu object:nil userInfo:dic];
        
        
        dispatch_queue_t imageDownloadQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(imageDownloadQueue, ^{
        
            NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", [[[dic valueForKey:@"data"] valueForKey:@"user"] valueForKey:@"iconUrl"]]];
            NSData *imageData = [NSData dataWithContentsOfURL:url];
            dispatch_async(dispatch_get_main_queue(), ^{
            
             [imageData writeToFile:[documentsDirectoryPath stringByAppendingPathComponent:@"MyImage.jpg"] options:NSAtomicWrite error:nil];
                
            });
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        
    }];

    return self;
}


@end
